package com.neuedu.bases;

/**
 * @author Wujg(helpbusiness @ 126.com)
 * @date 2023/8/21
 */

import com.neuedu.configs.PathConfig;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.logging.*;

public class Logger {

    private  java.util.logging.Logger logger;

    public Logger(String loggerName){

        try {

            // 创建一个logger
            logger = java.util.logging.Logger.getLogger(loggerName);
            logger.setLevel(Level.ALL);

            // 设置log属性
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
            String rq = now.format(formatterDate);
            String logName = PathConfig.path_logs + "/" + rq + ".log";

            Formatter formatter = new Formatter() {
                @Override
                public String format(LogRecord record) {
                    return String.format("%1$s - %2$tY-%2$tm-%2$td %2$tH:%2$tM:%2$tS - %3$s > %4$s() - %5$s %n",
                            record.getLevel(), record.getMillis(), record.getLoggerName(),
                            record.getSourceMethodName(), record.getMessage());
                }
            };

            // 创建一个handler，用于写入日志文件
            FileHandler fh = new FileHandler(logName, true);
            fh.setLevel(Level.INFO);
            fh.setFormatter(formatter);

            // 给logger添加handler
            logger.addHandler(fh);

            // 再创建一个handler，用于输出到控制台
            ConsoleHandler ch = new ConsoleHandler();
            ch.setLevel(Level.INFO);
            ch.setFormatter(formatter);
            logger.addHandler(ch);

        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void info(String msg) {
        logger.info(msg);
    }

    public void warn(String msg) {
        logger.warning(msg);
    }

    public void error(String msg)
    {
        logger.log(Level.SEVERE,msg);
    }



}